package org.confucianismframework.orm.pattern;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 实体名称匹配器
 * @author zy
 */
public class EntityNamePattern {

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 下划线转驼峰
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(toFirstLowerCase(str));
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 将字符串开头转为小写
     */
    public static String toFirstLowerCase(String str) {
        char[] chars = str.toCharArray();
        if (!Character.isUpperCase(chars[0])) {
            return str;
        }
        chars[0] += 32;
        return new String(chars);
    }


}
